import os
import sys
import time
from flask import Flask, request, jsonify
import pymongo
from bson import ObjectId
from pymongo import MongoClient

# Пример запроса по api
# {
# 	"table": "hpsm",
# 	"param": "open"
# }

# подключение к БД
def readDB(col, param):
	_ip = '10.211.55.10'
	_port = 27017
	_user = 'almaz'
	_password = 'almaz'
	_db = 'cerberus'
	client = MongoClient(_ip, _port, username=_user, password=_password, authSource=_db, authMechanism='SCRAM-SHA-1')
	client.server_info()
	collect = client[_db][col]
	with pymongo.timeout(10):
		data = list(collect.find(param))
	return data

# очистка от ключа _id
def cleanId(data):
	result = {'result': []}
	for res in data:
		tmp_res = dict()
		for k, v in res.items():
			if k != '_id':
				tmp_res[k] = v
		result['result'].append(tmp_res)
	return result

# разбор запроса API и формирование ответа
def parseApi(req):
	table = req.get('table')
	param = req.get('param')
	if param == 'open':
		db_res = readDB(table, {'Status': 'open'})
	result = cleanId(db_res)
	return result

app = Flask(__name__)
app.config['FLASK_APP'] = 'index'
app.config['DEBUG'] = True

#---------- API ----------
@app.route('/', methods=['GET'])
def index():
	ip = request.remote_addr
	return jsonify({'status': 'ok'})

@app.route('/api', methods=['POST'])
def api():
	ip = request.remote_addr
	if request.json:
		data = request.json
		reply = parseApi(data)
	return jsonify(reply), 200


if __name__ == "__main__":
	app.run()
